package org.piaohao.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.io.File;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.piaohao.interceptor.DriverCondition;
import org.piaohao.model.Driver;
import org.piaohao.util.string.JsonUtil;
import org.piaohao.util.string.UUIDGenerator;

/**
 * Created on : 2013-5-4, 17:22:19
 *
 * @author piaohao
 */
public class DriverController extends Controller {

    public static final String moduleName = "驾驶员档案模块";
    public DriverCondition dc;

    public void index() {
        render("/pages/driver/driver.jsp");
    }

    public void list() {
        try {
            Integer start = getParaToInt("start");
            Integer limit = getParaToInt("limit");
            String orgId = (String) getSessionAttr("orgId");
            List<Record> drivers = null;
            Long total = 0L;
            if (orgId.equals("0")) {
                drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id limit ?,?", start, limit);
                total = Db.queryLong("select count(*) from t_driver");
            } else {
                drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id where org_id=? limit ?,?", orgId, start, limit);
                total = Db.queryLong("select count(*) from t_driver where org_id=?", orgId);
            }
            renderJson(JsonUtil.printGrid(total, drivers));
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    public void add() {
        try {
            Driver driver = getModel(Driver.class);
            String para1 = getPara("birthday");
            DateFormat df = new SimpleDateFormat("yy-MM-dd");
            Date birthday = df.parse(para1);
            driver.set("birthday", new Timestamp(birthday.getTime()));
            if (driver.getStr("id") == null || driver.getStr("id").trim().equals("")) {
                driver.set("id", UUIDGenerator.getUUID());
                driver.save();
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void update() {
        try {
            Driver driver = getModel(Driver.class);
            String para1 = getPara("birthday");
            DateFormat df = new SimpleDateFormat("yy-MM-dd");
            Date birthday = df.parse(para1);
            driver.set("birthday", new Timestamp(birthday.getTime()));
            driver.update();
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void delete() {
        try {
            String[] idArr = getParaValues("ids");
            for (int i = 0; i < idArr.length; i++) {
                Driver.dao.deleteById(idArr[i]);
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void showDetail() {
        try {
            String id = getPara(0);
            Record driver = Db.findFirst("select d.* ,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id where d.id=?", id);
            setAttr("driver", driver);
            render("/pages/driver/detail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    @Before(DriverCondition.class)
    public void search() {
        try {
            StringBuilder sql = new StringBuilder();
            List<Object> paras = new ArrayList<Object>();
            dc.buildSql(sql, paras);
            Page<Driver> drivers = Driver.dao.paginate(dc.getPageNum() + 1, dc.getPageSize(), "select d.*,o.name orgName ", sql.toString(), paras.toArray());
            renderJson(JsonUtil.printGrid(new Long(drivers.getTotalRow()), drivers.getList()));
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    public void exportAll() {
        try {
            String startStr = getPara("start");
            int start = -1;
            if (startStr == null || startStr.equals("")) {
            } else {
                start = Integer.parseInt(startStr);
            }
            String orgId = (String) getSessionAttr("orgId");
            List<Record> drivers;
            if (start == -1) {
                if (orgId.equals("0")) {
                    drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id");
                } else {
                    drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id where org_id=?", orgId);
                }
            } else {
                if (orgId.equals("0")) {
                    drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id limit ?,?", start, 15);
                } else {
                    drivers = Db.find("select d.*,o.name orgName from t_driver d left join t_organization o on d.org_id=o.id where org_id=? limit ?,?", orgId, start, 15);
                }
            }

            File xls = new File(PathKit.getWebRootPath() + File.separator + "tmp", System.currentTimeMillis() + ".xls");
            WritableWorkbook book = Workbook.createWorkbook(xls);
            WritableSheet sheet = book.createSheet(" 第一页 ", 0);
            CellView view = new CellView();
            view.setAutosize(true);
            for (int i = 0; i < 9; i++) {
                sheet.setColumnView(i, 20);
            }
            sheet.addCell(new Label(0, 0, "姓名"));
            sheet.addCell(new Label(1, 0, "性别"));
            sheet.addCell(new Label(2, 0, "年龄"));
            sheet.addCell(new Label(3, 0, "出生日期"));
            sheet.addCell(new Label(4, 0, "身份证"));
            sheet.addCell(new Label(5, 0, "电话"));
            sheet.addCell(new Label(6, 0, "邮件"));
            sheet.addCell(new Label(7, 0, "文化程度"));
            sheet.addCell(new Label(8, 0, "家庭住址"));
            sheet.addCell(new Label(9, 0, "所属机构"));
            for (int row = 1; row <= drivers.size(); row++) {
                Record d = drivers.get(row - 1);
                sheet.addCell(new Label(0, row, d.getStr("name")));
                sheet.addCell(new Label(1, row, d.getStr("sex")));
                sheet.addCell(new Label(2, row, d.getInt("age").toString()));
                sheet.addCell(new Label(3, row, d.getTimestamp("birthday").toString()));
                sheet.addCell(new Label(4, row, d.getStr("id_card")));
                sheet.addCell(new Label(5, row, d.getStr("cellphone")));
                sheet.addCell(new Label(6, row, d.getStr("email")));
                sheet.addCell(new Label(7, row, d.getStr("education")));
                sheet.addCell(new Label(8, row, d.getStr("address")));
                sheet.addCell(new Label(9, row, d.getStr("orgName")));
            }
            book.write();
            book.close();
            renderFile(xls);
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }
}
